import 'package:flutter/material.dart';
import 'dart:math';
import '../models/morse_character.dart';
import '../services/morse_audio_service.dart';

class PracticePage extends StatefulWidget {
  final bool isMixedMode;
  
  const PracticePage({super.key, this.isMixedMode = false});

  @override
  State<PracticePage> createState() => _PracticePageState();
}

class _PracticePageState extends State<PracticePage> {
  final MorseAudioService _audioService = MorseAudioService();
  final Random _random = Random();
  
  String? selectedAnswer;
  bool hasAnswered = false;
  bool isLoading = false;
  int score = 0;
  int totalQuestions = 0;
  
  late MorseCharacter currentCharacter;
  late List<String> options;

  @override
  void initState() {
    super.initState();
    _generateNewQuestion();
  }

  @override
  void dispose() {
    _audioService.stop();
    super.dispose();
  }

  void _generateNewQuestion() {
    setState(() {
      hasAnswered = false;
      selectedAnswer = null;
      isLoading = false;
    });

    // 根据模式选择字符集
    List<MorseCharacter> availableCharacters;
    if (widget.isMixedMode) {
      availableCharacters = MorseData.characters;
    } else {
      // 默认只用字母
      availableCharacters = MorseData.letters;
    }

    // 随机选择当前字符
    currentCharacter = availableCharacters[_random.nextInt(availableCharacters.length)];
    
    // 生成选项（包含正确答案和3个错误答案）
    options = _generateOptions(currentCharacter, availableCharacters);
  }

  List<String> _generateOptions(MorseCharacter correct, List<MorseCharacter> pool) {
    final List<String> result = [correct.character];
    final List<MorseCharacter> others = pool.where((c) => c.character != correct.character).toList();
    
    // 随机选择3个错误选项
    while (result.length < 4 && others.isNotEmpty) {
      final randomChar = others[_random.nextInt(others.length)];
      if (!result.contains(randomChar.character)) {
        result.add(randomChar.character);
      }
      others.remove(randomChar);
    }
    
    // 打乱选项顺序
    result.shuffle(_random);
    return result;
  }

  Future<void> _playMorseCode() async {
    if (_audioService.isPlaying || hasAnswered) return;
    
    setState(() {
      isLoading = true;
    });
    
    try {
      await _audioService.playCharacter(currentCharacter);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void selectAnswer(String answer) {
    if (hasAnswered) return;
    
    setState(() {
      selectedAnswer = answer;
      hasAnswered = true;
      totalQuestions++;
      
      if (answer == currentCharacter.character) {
        score++;
      }
    });

    // 延迟后自动进入下一题
    Future.delayed(const Duration(milliseconds: 1500), () {
      if (mounted) {
        _generateNewQuestion();
      }
    });
  }

  void skipQuestion() {
    setState(() {
      totalQuestions++;
    });
    _generateNewQuestion();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 16),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: const Color(0xFF1E1E1E),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              '$score/$totalQuestions',
              style: const TextStyle(
                color: Color(0xFF00BFFF),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              // Header
              Column(
                children: [
                  Text(
                    widget.isMixedMode ? 'Mixed Practice' : 'Letter Recognition',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFFAAAAAA),
                    ),
                  ),
                  const SizedBox(height: 5),
                  const Text(
                    'What character is this?',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              
              const SizedBox(height: 30),
              
              // Score progress
              if (totalQuestions > 0)
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Accuracy: ${totalQuestions > 0 ? ((score / totalQuestions) * 100).toStringAsFixed(0) : '0'}%',
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        'Questions: $totalQuestions',
                        style: const TextStyle(
                          color: Color(0xFFAAAAAA),
                        ),
                      ),
                    ],
                  ),
                ),
              
              const SizedBox(height: 30),
              
              // Audio Player
              GestureDetector(
                onTap: _playMorseCode,
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    border: Border.all(
                      color: isLoading ? const Color(0xFFFFB74D) : const Color(0xFF00BFFF), 
                      width: 3,
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: isLoading
                      ? const CircularProgressIndicator(
                          color: Color(0xFFFFB74D),
                        )
                      : Icon(
                          _audioService.isPlaying ? Icons.volume_up : Icons.play_arrow,
                          size: 48,
                          color: const Color(0xFF00BFFF),
                        ),
                ),
              ),
              
              const SizedBox(height: 20),
              
              Text(
                'Tap to ${_audioService.isPlaying ? 'listen' : 'play'} morse code',
                style: const TextStyle(
                  color: Color(0xFFAAAAAA),
                  fontSize: 14,
                ),
              ),
              
              const SizedBox(height: 40),
              
              // Options Grid
              Expanded(
                child: GridView.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 15,
                  mainAxisSpacing: 15,
                  children: options.map((option) {
                    Color backgroundColor = const Color(0xFF1E1E1E);
                    Color borderColor = const Color(0xFF333333);
                    
                    if (hasAnswered && selectedAnswer == option) {
                      if (option == currentCharacter.character) {
                        backgroundColor = const Color(0xFF2E7D32);
                        borderColor = const Color(0xFF2E7D32);
                      } else {
                        backgroundColor = const Color(0xFFC62828);
                        borderColor = const Color(0xFFC62828);
                      }
                    } else if (hasAnswered && option == currentCharacter.character) {
                      // 显示正确答案
                      backgroundColor = const Color(0xFF2E7D32);
                      borderColor = const Color(0xFF2E7D32);
                    }
                    
                    return GestureDetector(
                      onTap: () => selectAnswer(option),
                      child: Container(
                        decoration: BoxDecoration(
                          color: backgroundColor,
                          border: Border.all(color: borderColor, width: 2),
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Center(
                          child: Text(
                            option,
                            style: const TextStyle(
                              fontSize: 28,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
              
              const SizedBox(height: 40),
              
              // Footer Actions
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  GestureDetector(
                    onTap: skipQuestion,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      decoration: BoxDecoration(
                        color: const Color(0xFF1E1E1E),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Text(
                        'Skip Question',
                        style: TextStyle(
                          color: Color(0xFFAAAAAA),
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  
                  if (hasAnswered)
                    GestureDetector(
                      onTap: _generateNewQuestion,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        decoration: BoxDecoration(
                          color: const Color(0xFF00BFFF),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: const Text(
                          'Next Question',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
